package com.naiterui.ehp.bs.wechat.service.impl;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.naiterui.ehp.bs.wechat.protocol.msg.template.TemplateMsg;
import com.naiterui.ehp.bs.wechat.protocol.msg.template.TemplateUrl;
import com.naiterui.ehp.bs.wechat.service.IAccessTokenService;
import com.naiterui.ehp.bs.wechat.service.ITemplateMsgApiService;
import com.naiterui.ehp.bs.wechat.utils.WeChatApiUtil;

/**
 * @author zhoupeipei
 * @date 2019-06-18 19:54
 * @since 1.0.0
 */
@Service
public class TemplateMsgApiServiceImpl implements ITemplateMsgApiService {
    @Autowired
    IAccessTokenService accessTokenService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void sendTemplateToUrl(String openId, String templateId, String url, Map<String, Object> data, Map<String, String> customColor) {
        TemplateUrl template = new TemplateUrl(openId, templateId, url);
        template.setData(this.createDataMap(data, customColor));
        WeChatApiUtil.sendTemplateMsg(accessTokenService.accessToken(), template);
    }

    private Map<String, TemplateMsg.Data> createDataMap(Map<String, Object> source, Map<String, String> customColor) {
        Map<String, TemplateMsg.Data> dataMap = new HashMap<>();
        source.keySet().forEach(key -> dataMap.put(key, new TemplateMsg.Data(source.get(key), customColor.get(key))));
        return dataMap;
    }
}
